package com.yhm.NIO.ServerSocketChannel对于客户端的读取数据操作交由线程池线程去处理;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class YhmNIOServer {


  public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    try {
      ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
      serverSocketChannel.configureBlocking(false);
      serverSocketChannel.bind(new InetSocketAddress(8080));

      while (true) {
        SocketChannel socketChannel = serverSocketChannel.accept();
        if( socketChannel==null )continue;
        System.out.println("服务端接收到客户端连接,RemoteAddress=" + socketChannel.getRemoteAddress() + ",Blocking=" + socketChannel.isBlocking());

        //交由线程池处理
        executorService.execute(new Runnable() {
          @Override
          public void run() {
            try {

              ByteBuffer readBuffer = ByteBuffer.allocate(1024);

              while (socketChannel.isOpen() && (socketChannel.read(readBuffer) != -1)) {
                if (readBuffer.position() > 0) break;
              }

              //接收数据
              readBuffer.flip();
              byte[] receiveBytes = new byte[readBuffer.limit()];
              readBuffer.get(receiveBytes);
              System.out.println("接收到客户端数据" + new String(receiveBytes));

              //发送数据
              ByteBuffer sendBuffer = ByteBuffer.wrap(("服务端返回" + Math.random() + "数据").getBytes());
              while (socketChannel.isOpen() && (socketChannel.write(sendBuffer) != -1)) {
                if (sendBuffer.position() > 0) {
                  break;
                }
              }
              socketChannel.close();
            } catch (Exception e) {

            }
          }
        });

      }
    } catch (IOException e) {
      e.printStackTrace();
    }
    executorService.shutdown();
  }


}
